package activity

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/internal/utils/errorhandler"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetActivityListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetActivityListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetActivityListLogic {
	return &BackendGetActivityListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetActivityListLogic) BackendGetActivityList(
	in *promotion.ActivityListReq,
) (*promotion.ActivityListResp, error) {
	// logx.Infof("BackendGetActivityList : %+v ", in)

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			switch orderBy.Field {
			case "id":
				orderBys = append(orderBys, model.PromotionActivityColumns.ID+order)
			case "sort":
				orderBys = append(orderBys, model.PromotionActivityColumns.Sort+order)
			case "createdAt":
				orderBys = append(orderBys, model.PromotionActivityColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	var activityType string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			case "type":
				activityType = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	var withCount int
	var preCount int64
	filterMap := make(map[string]map[string][]any)
	resp := &promotion.ActivityListResp{}
	if in.Ids != nil && len(*in.Ids) > 0 {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.PromotionActivityColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
			withCount = -1
			preCount = int64(len(vals))
		}
	}

	var statusIsSet bool
	var isAll bool
	statusMap := make(map[string][]any)
	switch activityType {
	case "1": // 全部
		statusMap["notEqualTo"] = []any{globalkey.StatusDeleted}
		isAll = true
	case "2": // 已生效
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusStarted},
		}
		statusIsSet = true
	case "3": // 正常
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusNormal},
		}
		statusIsSet = true
	case "4": // 已过期
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusFinished},
		}
		statusIsSet = true
	case "5": // 禁用
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusBanned},
		}
		statusIsSet = true
	case "6": // 回收站
		filterMap[model.PromotionActivityColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusDeleted},
		}
		statusIsSet = true
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
		withCount = 1
	}

	if in.Name != nil && len(strings.TrimSpace(*in.Name)) >= 2 {
		filterMap[model.PromotionActivityColumns.Name] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Name)},
		}
	}
	if in.Slug != nil && len(strings.TrimSpace(*in.Slug)) >= 2 {
		filterMap[model.PromotionActivityColumns.Slug] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Slug)},
		}
	}

	if in.ActivityType != nil {
		filterMap[model.PromotionActivityColumns.ActivityType] = map[string][]any{
			"equalTo": {*in.ActivityType},
		}
	}
	if in.ScopeType != nil {
		filterMap[model.PromotionActivityColumns.ScopeType] = map[string][]any{
			"equalTo": {*in.ScopeType},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.PromotionActivityColumns.CreatedAt] = createdAtMap

	var search string
	if in.Search != nil && len(strings.TrimSpace(*in.Search)) >= 2 {
		search = strings.TrimSpace(*in.Search)
	}

	// logrus.Info(fmt.Sprintf("BackendGetActivityList filterMap: %+v", filterMap))

	if isAll {
		ret, _, err := l.svcCtx.Activity.GetList(l.ctx, model.M{
			"search":    search,
			"statistic": "1",
		}, 5, filterMap)
		if err != nil {
			// return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			logx.Errorw("BackendGetActivityList GetList statistic err", logx.Field("detail", err.Error()))
		} else if len(ret) > 0 {
			statusStatisticMap := make(map[uint32]uint32)
			var total uint16
			for _, v := range ret {
				statusStatisticMap[uint32(v.Status)] = uint32(v.Sort)
				if v.Status != uint16(globalkey.StatusDeleted) {
					total += v.Sort
				}
			}
			statusStatisticMap[uint32(6)] = uint32(total)
			resp.StatusStatisticMap = statusStatisticMap
		}
	}

	if !statusIsSet {
		// logrus.Info(fmt.Sprintf("BackendGetActivityList in.Status: %+v", in.Status))
		statusIn := modelx.UniqueInterfaces(stati, 32)
		if len(statusIn) > 0 {
			statusMap["in"] = statusIn
		}
		if in.Status != nil {
			statusMap["equalTo"] = []any{*in.Status}
		}
		filterMap[model.PromotionActivityColumns.Status] = statusMap
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	} else {
		orderBy = model.PromotionActivityColumns.ID + " DESC"
	}
	var selectCols string
	if in.SkipContent != nil && *in.SkipContent > 0 {
		selectCols = strings.Join([]string{
			model.PromotionActivityColumns.ID,
			model.PromotionActivityColumns.Name,
			model.PromotionActivityColumns.Slug,
			model.PromotionActivityColumns.ActivityType,
			model.PromotionActivityColumns.ScopeType,
			model.PromotionActivityColumns.Sort,
			model.PromotionActivityColumns.TimesLimit,
			model.PromotionActivityColumns.GroupMode,
			model.PromotionActivityColumns.GroupType,
			model.PromotionActivityColumns.Status,
			model.PromotionActivityColumns.CreateStep,
			model.PromotionActivityColumns.CreatedAt,
		}, ",")
	}
	res, count, err := l.svcCtx.Activity.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"search":   search, // Todo: 暂未生效
		"orderBy":  orderBy,
		"select":   selectCols,
	}, withCount, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if restricted {
		count = preCount
	}
	resp.Total = uint64(count)

	if len(res) > 0 {
		var tids []any
		for _, v := range res {
			tids = append(tids, v.ID)
		}

		idMetumMap := make(map[uint64][]*model.PromotionActivityMetum)
		if in.WithMeta != nil && *in.WithMeta > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.PromotionActivityMetumColumns.ActivityID] = map[string][]any{
				"in": tids,
			}
			subFilterMap[model.PromotionActivityMetumColumns.MetaKey] = map[string][]any{
				"in": {
					"_thumbnail_id",
					"_thumbnail_url",
				},
			}
			list, _, err := l.svcCtx.Activity.GetMeta(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idMetumMap[v.ActivityID] = append(idMetumMap[v.ActivityID], v)
				}
			}
		}

		idMediaMap := make(map[uint64][]*promotion.MediaInfo)
		if in.WithMedia != nil && *in.WithMedia > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.PromotionAttachmentRelationshipColumns.ObjectID] = map[string][]any{
				"in": tids,
			}
			subFilterMap[model.PromotionAttachmentRelationshipColumns.ObjectType] = map[string][]any{
				"equalTo": {globalkey.AttachmentLogTypePromotion},
			}
			subFilterMap[model.PromotionAttachmentRelationshipColumns.AttachmentThumbnail] = map[string][]any{
				"equalTo": {1},
			}
			list, _, err := l.svcCtx.Activity.GetMedia(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idMediaMap[v.ObjectID] = append(idMediaMap[v.ObjectID], &promotion.MediaInfo{
						Uid:       &v.AttachmentRelationshipID,
						Id:        pointy.GetPointer(strconv.FormatUint(v.AttachmentID, 10)),
						Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
						Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
						Uri:       &v.AttachmentSource,
						Url:       &v.AttachmentImageURL,
						AltText:   &v.AttachmentImageAlt,
						MetaData:  &v.AttachmentImageMeta,
					})
				}
			}
		}

		for _, v := range res {
			var meta []*promotion.MetaInfo
			var media []*promotion.MediaInfo
			if ms, ok := idMetumMap[v.ID]; ok {
				var mediaId *string
				var mediaUrl *string
				for _, m := range ms {
					key := m.MetaKey
					if len(key) > 0 && m.MetaValue.Valid {
						val := m.MetaValue.String
						switch key {
						case "_thumbnail_id":
							mediaId = pointy.GetPointer(val)
						case "_thumbnail_url":
							mediaUrl = pointy.GetPointer(val)
						default:
							meta = append(meta, &promotion.MetaInfo{
								Key:   pointy.GetPointer(key),
								Value: pointy.GetPointer(val),
							})
						}
					}
				}
				if mediaUrl != nil {
					media = append(media, &promotion.MediaInfo{
						Id:        mediaId,
						Thumbnail: pointy.GetPointer(uint32(1)),
						Url:       mediaUrl,
					})
				}
			}

			if ms, ok := idMediaMap[v.ID]; ok {
				media = ms[:]
			}

			resp.List = append(resp.List, &promotion.ActivityInfo{
				Id:                    &v.ID,
				Name:                  &v.Name,
				Slug:                  &v.Slug,
				MemberRestriction:     &v.MemberRestriction,
				ActivityType:          pointy.GetPointer(uint32(v.ActivityType)),
				MutexType:             pointy.GetPointer(uint32(v.MutexType)),
				ScopeType:             pointy.GetPointer(uint32(v.ScopeType)),
				TimesLimit:            pointy.GetPointer(uint32(v.TimesLimit)),
				GroupMode:             pointy.GetPointer(uint32(v.GroupMode)),
				GroupType:             pointy.GetPointer(uint32(v.GroupType)),
				SeckillLimit:          pointy.GetPointer(uint32(v.SeckillLimit)),
				SeckillCancelDuration: pointy.GetPointer(uint32(v.SeckillCancelDuration)),
				SeckillNotifyDuration: pointy.GetPointer(uint32(v.SeckillNotifyDuration)),
				PackageType:           pointy.GetPointer(uint32(v.PackageType)),
				PackagePicId:          &v.PackagePicID,
				PackagePicUrl:         &v.PackagePicURL,
				Sort:                  pointy.GetPointer(uint32(v.Sort)),
				Status:                pointy.GetPointer(uint32(v.Status)),
				Step:                  pointy.GetPointer(uint32(v.CreateStep)),
				StartedAt:             pointy.GetPointer(modelx.FormatNullDotTime(v.StartedAt, "")),
				EndedAt:               pointy.GetPointer(modelx.FormatNullDotTime(v.EndedAt, "")),
				CreatedAt:             pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:             pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt:             pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				Meta:                  meta,
				Media:                 media,
			})
		}
	}

	return resp, nil
}
